package org.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 模拟着写一个根据实体类生成DDL自动建表的工具类(只能说勉强能用,以后有时间再精修)
 *
 * @author yexi
 */
public class TableUtils {
    public static Map<String, String> javaPropertyToSqlColumnMap = new HashMap<>();

    static {
        javaPropertyToSqlColumnMap.put("Integer", "int");
        javaPropertyToSqlColumnMap.put("Short", "tinyint");
        javaPropertyToSqlColumnMap.put("Long", "bigint");
        javaPropertyToSqlColumnMap.put("BigDecimal", "decimal(19,2)");
        javaPropertyToSqlColumnMap.put("Double", "double(10,2)");
        javaPropertyToSqlColumnMap.put("Float", "float");
        javaPropertyToSqlColumnMap.put("Boolean", "bit");
        javaPropertyToSqlColumnMap.put("String", "varchar(255)");
        javaPropertyToSqlColumnMap.put("Date", "datetime");
    }

    public static String createDDL(Class<?> obj, String tableName) {

        Field[] fields = obj.getDeclaredFields();
        StringBuilder sb = new StringBuilder(50);
        if (tableName == null || "".equals(tableName)) {
            //不传表名则默认使用类名做表名
            tableName = obj.getName();
            tableName = tableName.substring(tableName.lastIndexOf(".") + 1);
        }
        sb.append("create table ").append(tableName).append(" ( \r\n");
        boolean firstId = true;
        for (Field f : fields) {
            String column = f.getName();
            if (column.equals("serialVersionUID")) {
                continue;
            }
            String param = f.getType().getSimpleName();
            //一般第一个是主键
            sb.append(column);
            sb.append(" ").append(javaPropertyToSqlColumnMap.get(param)).append(" ");
            //类型转换
            if (firstId) {
                sb.append("AUTO_INCREMENT PRIMARY KEY ");
                firstId = false;
            }
            sb.append(",\n ");
        }
        String sql = null;
        sql = sb.toString();
        //去掉最后一个逗号
        int lastIndex = sql.lastIndexOf(",");
        sql = sql.substring(0, lastIndex) + sql.substring(lastIndex + 1);

        sql = sql.substring(0, sql.length() - 1) + " )ENGINE =INNODB DEFAULT  CHARSET= utf8;\r\n";
        return sql;

    }
}
